package com.zzh.myapplication.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.Toast;

import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import net.icarplus.car.R;
import net.icarplus.car.activity.OrderListDetailActivity;
import net.icarplus.car.adapter.CustomAdapter;
import net.icarplus.car.bean.MyOrderListBean;
import net.icarplus.car.constant.UrlValues;
import net.icarplus.car.datedialog.ShowPopeWindow;
import net.icarplus.car.lib.SwipeMenu;
import net.icarplus.car.lib.SwipeMenuCreator;
import net.icarplus.car.lib.SwipeMenuItem;
import net.icarplus.car.lib.SwipeMenuListView;
import net.icarplus.car.manager.BaseFragment;
import net.icarplus.car.service.PublicRequest;
import net.icarplus.car.tools.JsonUtil;
import net.icarplus.car.tools.LoadingUtil;
import net.icarplus.car.tools.SPUtils;
import net.icarplus.car.tools.T;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * 项目名称：icarplus-car-android
 * 类描述：
 * 创建人：Gophy
 * 创建时间：16/3/3 11:53
 * 修改人：Gophy
 * 修改时间：16/3/3 11:53
 * 修改备注：
 */

public class OrderFragment extends BaseFragment implements AdapterView.OnItemClickListener, SwipeMenuListView.IXListViewListener {
    private String msg;
    private SwipeMenuListView listView;
    private LoadingUtil loadingUtil;
    private List<MyOrderListBean> myOrders;
    private CustomAdapter adapter;
    private MyOrderListBean orderBean;
    private JSONArray array;
    private JSONObject jsons;
    private boolean isRefresh = false;
    private long time_car;
    private List<MyOrderListBean> data;
    private View HeaderView;
    private TextView search_voice;
    private ShowPopeWindow showPopeWindow;
    private String orderDate;
    private String userPhone;
    private String appNo;
    private String orderStatus;
    private Handler mHandler;

    @Override
    public void getsavedInstanceState(Bundle savedInstanceState) {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container) {
        return inflater.inflate(R.layout.fragment_order, null);
    }

    @Override
    public void initComponent(View view) {
        listView = (SwipeMenuListView) view.findViewById(R.id.lv_order);
        search_voice = (TextView) view.findViewById(R.id.search_voice);
        loadingUtil = new LoadingUtil(getActivity(), "查询中...");
        mHandler = new Handler();
        myOrders = createTestData();
        HeaderView = getActivity().getLayoutInflater().inflate(R.layout.listview_item_header, listView, false);
        this.loadingUtil.startShowLoading();
        listView.setXListViewListener(this);// 刷新的必要属性
        listView.setPullLoadEnable(false);// 设置让它上拉，FALSE为不让上拉，便不加载更多数据
        listView.setMenuCreator(creator);
    }

    // 适配
    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }

    public List<MyOrderListBean> createTestData() {
        data = new ArrayList<MyOrderListBean>();
        showPopeWindow = new ShowPopeWindow();
        setOrderListsParams();
        return data;
    }

    SwipeMenuCreator creator = new SwipeMenuCreator() {

        @Override
        public void create(SwipeMenu menu, View view) {
            // create "open" item
            SwipeMenuItem openItem = new SwipeMenuItem(
                    getActivity());
            // set item background
            openItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
                    0x3F, 0x25)));
            // set item width
            openItem.setWidth(dp2px(90));
            // set item title
            openItem.setTitle("取消订单");
            // set item title fontsize
            openItem.setTitleSize(18);
            // set item title font color
            openItem.setTitleColor(Color.WHITE);
            // add to menu
            menu.addMenuItem(openItem);

            /*// create "delete" item
            SwipeMenuItem deleteItem = new SwipeMenuItem(
                    getActivity());
            // set item background
            deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
                    0x3F, 0x25)));
            // set item width
            deleteItem.setWidth(dp2px(90));
            // set a icon
            //deleteItem.setIcon(R.mipmap.ic_delete);
            // add to menu*/
            //menu.addMenuItem(deleteItem);
        }
    };

    @Override
    public void setListener() {
        search_voice.setOnClickListener(this);
        listView.setOnItemClickListener(this);
        listView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                MyOrderListBean bean = myOrders.get(position);
                listView.smoothOpenMenu(position);
                switch (index) {
                    case 0:
                        if (bean.getOrderStatus().equals("待取车") || bean.getOrderStatus().equals("待预付")) {
                            //myOrders.remove(position);
                            deleteOrder(bean.getOrderNum());
                        }

                        adapter.notifyDataSetChanged();
                        break;
                }
                return false;
            }
        });
        // set SwipeListener
        listView.setOnSwipeListener(new SwipeMenuListView.OnSwipeListener() {

            @Override
            public void onSwipeStart(int position) {
                // swipe start
            }

            @Override
            public void onSwipeEnd(int position) {
                // swipe end
            }
        });
    }

    //取消订单
    public void deleteOrder(String orderNum) {
        JSONObject object = new JSONObject();
        try {
            object.put("mobile", userPhone);
            object.put("appNo", orderNum);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        PublicRequest.doPostRequest(UrlValues.CANCEL_RENT_CAR_ORDER_URL, handler, object, 200, 100);
    }

    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 200:
                    T.show(getActivity(), "取消成功", 1);
                    data.clear();
                    setOrderListsParams();
                    break;
                case 100:
                    T.show(getActivity(), "取消失败", 1);
                    break;
            }
        }
    };

    @Override
    public void onAfterInit() {
    }


    private void setOrderListsParams() {
        JSONObject json = new JSONObject();
        userPhone = SPUtils.getString(getActivity(), "LoginInfo", "");
        try {
            json.put("mobile", userPhone);
            json.put("orderFlag", "");
            json.put("orderType", "01");
            json.put("pageNum", "1");
            json.put("totalNum", "10");
            json.put("rentType", "01");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (!isRefresh) {
            this.loadingUtil.startShowLoading();
        }
        OkHttpUtils.get().url(UrlValues.MY_ORDERS).addParams("input", json.toString()).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e) {
            }

            @Override
            public void onResponse(String response) {
                getMyOrdersResponse(response);
            }
        });
    }


    private void getMyOrdersResponse(String data1) {
        try {
            JSONObject result = new JSONObject(data1.toString());
            if (JsonUtil.isValid(data1)) {
                array = result.getJSONArray("queryList");
                this.loadingUtil.stopShowLoading();
                // mSwipeRefreshLayout.setRefreshing(false);
                for (int i = 0; i < array.length(); i++) {
                    jsons = array.getJSONObject(i);
                    msg = jsons.getString("orderType");
                    orderDate = jsons.getString("applyTime");
                    String[] date = orderDate.split("\\ ");
                    orderBean = new MyOrderListBean();
                    orderBean.setTitle(date[0]);
                    appNo = jsons.getString("appNo");
                    orderBean.setOrderNum(appNo);
                    orderBean.setOrderCarName("北汽E200");
                    orderBean.setOrderCarNum(jsons.getString("licenseNo"));
                    orderStatus = jsons.getString("statusName");
                    orderBean.setOrderStatus(orderStatus);
                    if (msg.equalsIgnoreCase("01")) {
                        orderBean.setCarPic(R.mipmap.icon_shi);
                    } else if (msg.equalsIgnoreCase("02")) {
                        orderBean.setCarPic(R.mipmap.icon_ri);
                    }
                    if (msg.equalsIgnoreCase("03")) {
                        orderBean.setCarPic(R.mipmap.icon_yu);
                    }
                    data.add(orderBean);
                }

                if (data.size() > 0) {
                    adapter = new CustomAdapter(getActivity(), data);
                    adapter.notifyDataSetChanged();
                }
            } else {
                Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                this.loadingUtil.stopShowLoading();
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }


        if (data != null) {
            listView.setAdapter(adapter);
            listView.setOnScrollListener(adapter);

        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.search_voice:
                showPopeWindow.ShowPopuWindow(getActivity(), search_voice, R.layout.order_fragment);
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position - 1 >= 0) {
            MyOrderListBean bean = myOrders.get(position - 1);
            String setOrderNum = bean.getOrderNum();
            String orderCarNum = bean.getOrderCarNum();
            String orderStatus = bean.getOrderStatus();
            Intent intent = new Intent();
            intent.putExtra("setOrderNum", setOrderNum);
            intent.putExtra("orderCarNum", orderCarNum);
            intent.putExtra("applyTime", orderDate);
            intent.putExtra("orderStatus", orderStatus);
            intent.setClass(getActivity(), OrderListDetailActivity.class);
            startActivity(intent);
        }
    }

    /***
     * 停止刷新
     */
    private void onLoad() {
        listView.stopRefresh();
        listView.stopLoadMore();
        listView.setRefreshTime("刚刚");
    }

    // 刷新
    @Override
    public void onRefresh() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                data.clear();
                setOrderListsParams();
                onLoad();
            }
        }, 3000);
    }

    // 加载更多
    @Override
    public void onLoadMore() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                data.clear();
                setOrderListsParams();
                onLoad();
            }
        }, 3000);
    }
}
